import React, { Component, createRef } from 'react'
import {
  Card,
  Button, 
  Form,
  // Icon,
  Input,
  Spin,
  DatePicker
} from 'antd'
import E from 'wangeditor'
import moment from 'moment'
import {
  getArticleById,
  saveArticleById
} from '../../api'
import './edit.less'

// console.log(E)

// import { withRouter } from 'react-router-dom'

const fromItemLayout = {
  labelCol: {
    span: 4
  },
  wrapperCol: {
    span: 20
  }
}

// @withRouter
@Form.create()

class Edit extends Component {
  constructor () {
    super()
    this.state = {
      titleValidateStatus: '',
      titleHelp: '',
      articleId: null,
      isLoading: false
    }
    this.editorRef = createRef()
  }

  initEditor = () => {
    this.editor = new E(this.editorRef.current)
    
    // 监听编辑器的change事件
    this.editor.customConfig.onchange = (html) => {
      // html 即变化之后的内容
      // console.log(html)
      // 将取到的值，（通过setFieldsValue）赋值给表单的content字段
      this.props.form.setFieldsValue({
        content: html
      })
    }

    this.editor.create()
  }

  componentDidMount() {
    this.initEditor()
    // console.log('dddddd', this.props)
    this.setState({
      isLoading: true
    })
    getArticleById(this.props.match.params.id)
      .then(res => {
        console.log(res)
        const { id, ...data } = res
        data.createAt = moment(data.createAt)
        this.props.form.setFieldsValue(data)

        // this.props.form.setFieldsValue({
        //   title: res.title,
        //   author: res.author,
        //   amount: res.amount,
        //   content: res.content,
        //   createAt: moment(res.createAt)
        // })

        // 设置富文本编辑器的问题
        this.editor.txt.html(data.content)
      })
      .finally(() => {
        this.setState({
          isLoading: false
        })
      })
  }

  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        console.log(values.createAt.valueOf())
        console.log('Received values of form: ', values);
        const data = Object.assign({}, values, {
          createAt: values.createAt.valueOf()
        })

        // console.log(data)

        this.setState({
          isLoading: true
        })
        saveArticleById(this.props.match.params.id, data)
          .then(res => {
            console.log(res)
            // 页面跳转
            this.props.history.push('/admin/article')
          })
          .finally(() => {
            this.setState({
              isLoading: false
            })
          })
      }
    });
  }

  render() {
    // console.log(this.props)
    const { getFieldDecorator } = this.props.form;
    return (
      <Card 
          title="编辑文章" 
          extra={<Button onClick={this.props.history.goBack}>取消</Button>} 
          style={{ width: '100%' }}
        >
        <Spin spinning={this.state.isLoading}>
          <Form 
            onSubmit={this.handleSubmit} 
            {...fromItemLayout}

          >
            <Form.Item
              label="标题"
              validateStatus={this.state.titleValidateStatus}
              help={this.state.titleHelp}
            >
              {getFieldDecorator('title', {
                rules: [
                  { required: true, message: '文章标题不能为空!' },
                  // { min: 4, message: '文章标题最短是4位!' },
                  // { max: 10, message: '文章标题最长是10!' },
                  // {
                  //   validator: (rule, value, callback) => {
                  //     console.log(rule, value, callback)
                  //     if ( value != '123') {
                  //       this.setState({
                  //         titleValidateStatus: 'error',
                  //         titleHelp: 'title不正确'
                  //       })
                  //     } else {
                  //       this.setState({
                  //         titleValidateStatus: '',
                  //         titleHelp: ''
                  //       })
                  //     }
                  //     callback()
                  //   }
                  // }
                ],
                initialValue: '这是一个初始值'
              })(
                <Input
                  placeholder="文章标题"
                />,
              )}
            </Form.Item>
            <Form.Item
              label="作者"
            >
              {getFieldDecorator('author', {
                rules: [
                  { required: true, message: '阅读量是必须的' }
                ],
              })(
                <Input
                  placeholder="作者"
                />,
              )}
            </Form.Item>
            <Form.Item
              label="阅读量"
            >
              {getFieldDecorator('amount', {
                rules: [
                  { required: true, message: '作者不能为空!' }
                ],
              })(
                <Input
                  placeholder="0"
                />,
              )}
            </Form.Item>
            <Form.Item
              label="创建时间"
            >
              {getFieldDecorator('createAt', {
                rules: [
                  { required: true, message: '创建时间是必须的' }
                ],
              })(
                <DatePicker showTime format="YYYY-MM-DD HH:mm:ss" />,
              )}
            </Form.Item>
            <Form.Item
              label="内容"
            >
              {getFieldDecorator('content', {
                rules: [
                  { required: true, message: '内容不能为空!' }
                ],
              })(
                <div className="qf-editor" ref={this.editorRef} />,
              )}
            </Form.Item>
            <Form.Item
              wrapperCol={{
                offset: fromItemLayout.labelCol.span
              }}
            >
              <Button type="primary" htmlType="submit" className="login-form-button">
                保存
              </Button>
              或 <Button onClick={this.props.history.goBack}>取消</Button>
            </Form.Item>
          </Form>
        </Spin>
      </Card>
    )
  }
}

export default Edit
